<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');

/**
 * TYPOlight webCMS
 *
 * The TYPOlight webCMS is an accessible web content management system that 
 * specializes in accessibility and generates W3C-compliant HTML code. It 
 * provides a wide range of functionality to develop professional websites 
 * including a built-in search engine, form generator, file and user manager, 
 * CSS engine, multi-language support and many more. For more information and 
 * additional TYPOlight applications like the TYPOlight MVC Framework please 
 * visit the project website http://www.typolight.org.
 *
 * PHP version 5
 * @copyright  Martin Komara 2007 
 * @author     Martin Komara 
 * @package    CatalogModule 
 * @license    GPL 
 * @filesource
 */


/**
 * Class ModuleCatalogListing 
 *
 * @copyright  Martin Komara 2007 
 * @author     Martin Komara 
 * @package    Catalog
 */
class ModuleCatalogListing extends ModuleListing
{
    protected function compile()
    {
        $objType = $this->Database->prepare("SELECT dca FROM tl_catalog_types where tableName=?")
            ->limit(1)
            ->execute($this->list_table);
            
        if ($objType->numRows > 0 && $objType->dca)
        {
            $GLOBALS['TL_DCA'][$this->list_table] = unserialize($objType->dca);
        } 
        
        $this->changeCondition();
        
        parent::compile();
    }
    
    private function changeCondition()
    {
        if (strlen($this->list_where))
        {
            $this->list_where = preg_replace_callback('/\b([a-z_][\w_]*)\b\s+(not\s+)?in\s+\(([^\)]+)\)/i', array($this, 'replaceCondition'), $this->list_where);
        }
    }
    
    private function replaceCondition($matches)
    {
        $col = $matches[1];
        $operator = strlen($matches[2]) ? '=' : '!=';
        $ids = $matches[3];
        
        // only change query for tags
        if ($GLOBALS['TL_DCA'][$this->list_table]['fields'][$col]['eval']['catalog']['type'] != 'tags')
        {
            return $matches[0];
        }
        $fieldId = $GLOBALS['TL_DCA'][$this->list_table]['fields'][$col]['eval']['catalog']['fieldId'];
        $itemTableIdCol = 'id';//$GLOBALS['TL_DCA'][$this->list_table]['fields'][$col]['eval']['catalog']['itemTableIdCol'];
        return "(SELECT COUNT(*) FROM tl_catalog_rel WHERE item_id={$this->list_table}.$itemTableIdCol AND field_id=$fieldId AND related_id IN ($ids)) $operator 0";
    }
    
    protected function formatValue($k, $value)
    {
        $raw = $value;
        $value = parent::formatValue($k, $value);
        
        $fieldConf = &$GLOBALS['TL_DCA'][$this->list_table]['fields'][$k];
        
        // select
        if ($fieldConf['eval']['catalog']['type'] == 'select' && $fieldConf['options'])
        {
            $value = $fieldConf['options'][$value];
        }
         
        // tags
        if ($fieldConf['eval']['catalog']['type'] == 'tags' && $fieldConf['options'])
        {
            $selectedOptions = explode(',', $value);
            $selectedValues = array_intersect_key($fieldConf['options'], array_flip($selectedOptions));
            $value = implode(', ', $selectedValues); 
        }
        
        if ($fieldConf['eval']['catalog']['type'] == 'file' && !empty($value))
        {
            $files = $fieldConf['eval']['catalog']['multiple'] ? deserialize($raw) : array($value);
            
            $values = array();
            foreach ($files as $locValue)
            {
                $file = new File($locValue);
                $path = $locValue;
                $convertToImage = $file->isGdImage && $fieldConf['eval']['catalog']['showImage'];
                    
                if ($convertToImage)
                {
                    $w = $fieldConf['eval']['catalog']['imageWidth'] ? $fieldConf['eval']['catalog']['imageWidth'] : '';
                    $h = $fieldConf['eval']['catalog']['imageHeight'] ? $fieldConf['eval']['catalog']['imageHeight'] : '';
                    $s = $this->urlEncode($locValue);
                    $locValue = "<img src=\"image.php?src=$s&amp;width=$w&amp;height=$h\" alt=\"\"/>";
                }
                
                if ($fieldConf['eval']['catalog']['showLink'])
                {
                    $text = $convertToImage ? $locValue : basename($path);
                    $locValue = "<a ".($file->isGdImage ? 'rel="lightbox"' : '')." href=\"$path\">$text</a>";
                }
                
                $values[] = $locValue;
            }
            
            $value = implode($fieldConf['eval']['catalog']['showImage'] ? '' : ', ', $values);
        }
        
        if ($fieldConf['eval']['catalog']['type'] == 'url' && $fieldConf['eval']['catalog']['showLink'] && !empty($value))
        {
            $value = "<a href=\"$value\">$value</a>";
        }
        
        if ($value)
        {
            switch ($fieldConf['eval']['catalog']['formatFunction'])
            {
                case 'string':
                    $value = sprintf($fieldConf['eval']['catalog']['formatStr'], $value);
                    break;
                    
                case 'number':
                    $decimalPlaces = is_numeric($fieldConf['eval']['catalog']['formatStr']) ? 
                        intval($fieldConf['eval']['catalog']['formatStr']) : 
                        0;
                    $value = number_format($value, $decimalPlaces, 
                        $GLOBALS['TL_LANG']['MSC']['decimalSeparator'],
                        $GLOBALS['TL_LANG']['MSC']['thousandsSeparator']);
                    break;
                    
                case 'money':
                    $value = money_format($fieldConf['eval']['catalog']['formatStr'], $value);
                    break;
                    
                case 'date':
                    $value = date($fieldConf['eval']['catalog']['formatStr'], $raw);
                    break;
            }
        }
        
        return $value;
    }
}

?>